<?php


namespace app\common\service;


use app\common\model\BaseModel;
use EasyWeChat\Factory;
use think\Cache;

class EasyWechatService
{
    //微信配置
    private $config;
    //支付
    private $payment;
    //小程序
    protected $wxapp;

    public function __construct()
    {
        $this->config = config('wechat');
        $this->payment = Factory::payment($this->config);
        $this->wxapp = Factory::miniProgram($this->config);
    }

    public function app()
    {
        return $this->payment;
    }

    /**
     * 支付
     */
    public function unify($orderNo, $total_price, $openId, $notifyUrl, $body = '可语')
    {
        $res = $this->payment->order->unify([
            'out_trade_no' => $orderNo,
            'total_fee' => $total_price * 100,
            'openid' => $openId,
            'trade_type' => 'JSAPI',
            'body' => $body,
            'notify_url' => $notifyUrl
        ]);
        $result = $this->paymentResult($res);
        $json = $this->payment->jssdk->bridgeConfig($result['prepay_id'], false);
        $json['out_trade_no'] = $orderNo;
        return $json;
    }

    /**
     * 商户号查询订单
     */
    public function find($orderNo)
    {
        $res = $this->payment->order->queryByOutTradeNumber($orderNo);
        $result = $this->paymentResult($res);
        if ($result['trade_state'] !== 'SUCCESS') {
            BaseModel::error($result['trade_state'], $result['trade_state_desc']);
        }
        return $result;
    }

    /**
     * 小程序登录
     */
    public function wxappAuth($code)
    {
        $res = $this->wxapp->auth->session($code);
        if (isset($res['errcode']) && $res['errcode']) {
            BaseModel::error($res['errcode'], $res['errmsg']);
        }
        $sessionKey = Cache::get('session_key_'.$res['openid']);
        if (!$sessionKey || $sessionKey != $res['session_key']) {
            Cache::set('session_key_'.$res['openid'], $res['session_key'], 7200);
        }
        return $res;
    }

    /**
     * 小程序码
     */
    public function wxacode($scene, $page)
    {
        $response = $this->wxapp->app_code->getUnlimit($scene ?? 'choi', [
            'page' => $page ?? ''
        ]);
        if (is_array($response) && isset($response['errcode']) && $response['errcode']) {
            BaseModel::error($response['errcode'], $response['errmsg']);
        }
        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/wxacode/', md5($page.$scene).'.png');
            return request()->domain().'/uploads/wxacode/'.$filename;
        }
    }

    /**
     * 支付结果验证
     * @param $res
     * @return mixedz
     */
    private function paymentResult($res)
    {
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            return $res;
        } else {
            BaseModel::error($res['return_code'], $res['return_msg']);
        }

    }

    /**
     * 小程序解密
     */
    public function decryptData($sessionKey, $iv, $encryptedData)
    {
        return $this->wxapp->encryptor->decryptData($sessionKey, $iv, $encryptedData);
    }

    /**
     * 小程序过滤违规词
     */
    public function checkText($content)
    {
        $res = $this->wxapp->content_security->checkText($content);
        if (isset($res['errcode']) && $res['errcode']) {
            BaseModel::error($res['errcode'], '您的内容存在违规');
        }
        return true;
    }

    /**
     * 小程序订阅消息
     */
    public function send($data)
    {
        return $this->wxapp->subscribe_message->send($data);
    }





}